package com.stud.seckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stud.seckill.common.enums.CacheKeyEnum;
import com.stud.seckill.common.config.CacheService;
import com.stud.seckill.common.exception.Asserts;
import com.stud.seckill.mapper.GoodsMapper;
import com.stud.seckill.entity.GoodsEntity;
import com.stud.seckill.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 商品表 服务实现类
 * </p>
 *
 * @author Libra
 * @since 2024-03-30
 */
@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper, GoodsEntity> implements GoodsService {

    @Autowired
    private CacheService cacheService;

    @Override
    public GoodsEntity get(Long id) {
        GoodsEntity goods = (GoodsEntity) cacheService.get(CacheKeyEnum.商品, id);
        if (goods == null) {
            goods = this.getBaseMapper().selectById(id);
            cacheService.set(CacheKeyEnum.商品, id, goods);
        }
        return goods;
    }

    @Override
    public void subStock(Long id, Integer stockCount) {
        // 扣减库存
        LambdaUpdateWrapper<GoodsEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.setSql("goods_stock=goods_stock-" + stockCount);
        updateWrapper.eq(GoodsEntity::getId, id);
        updateWrapper.gt(GoodsEntity::getGoodsStock, 0);
        boolean isResult = this.update(updateWrapper);
        if (!isResult) {
            Asserts.fail("扣减库存失败");
        }
        // 清除缓存
        cacheService.delete(CacheKeyEnum.商品, id);
    }

    @Override
    public List<GoodsEntity> selectList(GoodsEntity goods) {
        LambdaQueryWrapper<GoodsEntity> queryWrapper = Wrappers.lambdaQuery();
        return this.getBaseMapper().selectList(queryWrapper);
    }

    @Override
    public void initStock() {
        LambdaUpdateWrapper<GoodsEntity> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(GoodsEntity::getGoodsStock, 100);
        updateWrapper.lt(GoodsEntity::getGoodsStock, 100);
        this.update(updateWrapper);
    }

}
